package com.spider.moudle.consumer;

import com.spider.moudle.api.realize.AbstractConsumer;
import com.spider.moudle.entity.Setting;
import com.spider.moudle.entity.TaskType;
import com.spider.moudle.factory.ExecutorServiceFactoy;
import com.spider.moudle.factory.NamedThreadFactory;
import com.spider.moudle.util.CenterExecutorUtil;
import com.spider.moudle.worker.StandardWorker;

import java.util.concurrent.ExecutorService;

/**
 * Created by Linbo Hu on 2017/12/18.
 * 一个标准的消费者
 */
public class StartardConsumer extends AbstractConsumer {


    private Setting setting;

    public StartardConsumer(Setting setting) {
        this.setting = setting;
    }

    @Override
    public void speech() {
        ExecutorService executorService = null;
        try {
            executorService = ExecutorServiceFactoy.buildExecutorService(setting.getSpeech_work_count(), "消费者", new NamedThreadFactory(setting.getName(), "speech"));
            for (int i = 0; i < setting.getSpeech_work_count(); i++) {
                executorService.execute(new StandardWorker(setting, TaskType.SPEECH));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(executorService != null) {
                executorService.shutdown();
            }
        }
    }

    @Override
    public void user() {
        ExecutorService executorService = null;
        try {
            executorService = ExecutorServiceFactoy.buildExecutorService(setting.getUser_work_count(), "消费者", new NamedThreadFactory(setting.getName(), "user"));
            for (int i = 0; i < setting.getUser_work_count(); i++) {
                executorService.execute(new StandardWorker(setting, TaskType.USER));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(executorService != null) {
                executorService.shutdown();
            }
        }
    }
}
